package com.example.administrator.szb.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.UserBase;
import com.example.administrator.szb.bean.Yzm;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.ChangeStatuUtil;
import com.example.administrator.szb.util.CheckMsgUtils;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.JPushUtils;
import com.example.administrator.szb.util.KeyboardChangListenerUitl;
import com.example.administrator.szb.util.SPUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/12/18.
 */

public class LoginNewActivity_two extends BaseActivity {
    @Bind(R.id.login_password_login)
    RadioButton loginPasswordLogin;
    @Bind(R.id.login_rg)
    RadioGroup loginRg;
    @Bind(R.id.login_ll_password)
    LinearLayout loginLlPassword;
    @Bind(R.id.login_ll_yzm)
    LinearLayout loginLlYzm;
    @Bind(R.id.login_image_back)
    LinearLayout loginImageBack;
    @Bind(R.id.login_yzm_login)
    RadioButton loginYzmLogin;
    @Bind(R.id.login_edit_pass)
    EditText loginEditPass;
    @Bind(R.id.login_edit_password)
    EditText loginEditPassword;
    @Bind(R.id.login_text_wjmm)
    TextView loginTextWjmm;
    @Bind(R.id.login_edit_yzm)
    EditText loginEditYzm;
    @Bind(R.id.login_text_yzm)
    TextView loginTextYzm;
    @Bind(R.id.login_button_login)
    Button loginButtonLogin;
    @Bind(R.id.login_button_register)
    Button loginButtonRegister;

    String phone_num;//手机号
    String yzm_code;//验证码
    String password;//密码
    int time = 60;//获取验证码倒计时

    String code_yzm;//请求下来的验证码
    @Bind(R.id.login_sv_for_edit)
    ScrollView loginSvForEdit;
    private int login_tpye = 0;//0代表密码登录，1代表验证码登录


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity_new_two);

        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        loginSvForEdit.postDelayed(new Runnable() {
            @Override
            public void run() {
                loginSvForEdit.fullScroll(ScrollView.FOCUS_DOWN);
            }
        },500);

        initListener();
    }

    @Override
    protected void setBarColor() {
        ChangeStatuUtil.setTranslucentStatus(this);
    }

    private void initListener() {
        loginRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i) {
                    case R.id.login_password_login:
                        loginLlPassword.setVisibility(View.VISIBLE);
                        loginLlYzm.setVisibility(View.GONE);
                        login_tpye = 0;
                        break;
                    case R.id.login_yzm_login:
                        loginLlPassword.setVisibility(View.GONE);
                        loginLlYzm.setVisibility(View.VISIBLE);
                        login_tpye = 1;
                        break;
                }
            }
        });

        //对键盘的监听
        KeyboardChangListenerUitl.KeyboardChangListener(this, new KeyboardChangListenerUitl.KeyboardCallback() {
            @Override
            public void doSomeThing() {
                loginSvForEdit.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loginSvForEdit.smoothScrollTo(0, loginSvForEdit.getHeight());
                    }
                }, 0);
            }
        });
        loginTextYzm.setEnabled(false);
        loginTextYzm.setTextColor(Color.parseColor("#ffbcbcbc"));
        loginEditPass.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (CheckMsgUtils.isMobileNO(loginEditPass.getText().toString().trim())){
                    loginTextYzm.setEnabled(true);
                    loginTextYzm.setTextColor(getResources().getColor(R.color.white));
                }else {
                    loginTextYzm.setEnabled(false);
                    loginTextYzm.setTextColor(Color.parseColor("#ffbcbcbc"));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
//       final View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
//        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                rootView.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        if (isKeyboardShown(rootView)) {
//                            //onKeyBoardShow();
//                            //Toasts.show(LoginNewActivity_two.this, "ff", Toast.LENGTH_SHORT);
//                            loginSvForEdit.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    loginSvForEdit.smoothScrollTo(0, loginSvForEdit.getHeight());
//                                }
//                            }, 0);
//
////                            作者：fish119
////                            链接：http://www.jianshu.com/p/6a9f979c7ba8
////                            來源：简书
////                            著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
//                        } else {
//
//                        }
//                    }
//                },0);
//
//            }
//        });

    }

//    /**
//     * 判断软键盘是否打开
//     *
//     * @param rootView 最上层布局
//     * @return 打开：true，隐藏：false
//     */
//    private boolean isKeyboardShown(View rootView) {
//        final int softKeyboardHeight = 100;
//        Rect r = new Rect();
//        rootView.getWindowVisibleDisplayFrame(r);
//        DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
//        int heightDiff = rootView.getBottom() - r.bottom;
//        return heightDiff > softKeyboardHeight * dm.density;
//    }


    @OnClick({R.id.login_image_back, R.id.login_text_wjmm, R.id.login_text_yzm, R.id.login_button_login, R.id.login_button_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_image_back:
                goHome();
                break;
            case R.id.login_text_wjmm:
                startActivity(new Intent(this, ForgetPasswordActivity.class));
                break;
            case R.id.login_text_yzm:
                requestYzm();
                break;
            case R.id.login_button_login:
                loginSzb();
                break;
            case R.id.login_button_register:
                startActivity(new Intent(this,RegisterActivity_info.class));
                break;
        }
    }

    /**
     * 执行登录
     */
    private void loginSzb() {
        try {
            boolean flag = checkInfo();
            if (flag) {
                requestLogin();
            } else {
            }
        } catch (Exception e) {
        }
    }

    /**
     * 执行登录请求
     */
    private void requestLogin() {

        loginButtonLogin.setEnabled(false);
        loginButtonRegister.setEnabled(false);
        DialogUtil.showIsoProgressbar(LoginNewActivity_two.this, "登录中");
        Map<String,Object> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("tel", phone_num);
        if (login_tpye == 0) {
            map.put("pass", password);
            map.put("type", "1");
        } else {
            map.put("type", "0");
        }
       // String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_LOGIN;
        HttpUtils.post(activity,url, map, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                UserBase userBase = JSON.parseObject(str,new TypeReference<UserBase>(){});
                SPUtils.setDatas(SPUtils.USER_ID,userBase.getId());
                SPUtils.setDatas(SPUtils.USER_PHONE,phone_num);
                //JPushUtils.login(phone_num,userBase.getJpushpass());
                JPushUtils.register(phone_num,userBase.getJpushpass());
                JPushUtils.setALias(LoginNewActivity_two.this,phone_num);
                SPUtils.setDatas(SPUtils.USER_BASE,str);
                DialogUtil.dialog_ios.dismiss();
                DialogUtil.showToast(LoginNewActivity_two.this, "登录成功");
                goHome();
            }

            @Override
            public void onFailure(int requestCode, String str) {
                DialogUtil.dialog_ios.dismiss();
                loginButtonLogin.setEnabled(true);
                loginButtonRegister.setEnabled(true);
                DialogUtil.showToast(LoginNewActivity_two.this, str);
            }
        });

    }

    /**
     * 检查输入信息
     *
     * @return
     */

    private boolean checkInfo() {
        phone_num = loginEditPass.getText().toString();
        password = loginEditPassword.getText().toString();
        yzm_code = loginEditYzm.getText().toString();

        if (TextUtils.isEmpty(phone_num)) {
            DialogUtil.showToast(this, "请输入手机号");
        } else if (!CheckMsgUtils.isPhone(phone_num)) {
            DialogUtil.showToast(this, "请检查手机格式");
        } else if (login_tpye == 0 && TextUtils.isEmpty(password)) {
            DialogUtil.showToast(this, "请输入密码");
        } else if (login_tpye == 1 && TextUtils.isEmpty(yzm_code)) {
            DialogUtil.showToast(this, "请输入验证码");
        }
         else if(login_tpye == 1 && !(yzm_code.equals(code_yzm))){
           DialogUtil.showToast(this,"验证码有误");
        }
        else {
            return true;
        }

        return false;
    }

    /**
     * 执行验证码操作
     */
    private void requestYzm() {
        phone_num = loginEditPass.getText().toString();

        if (TextUtils.isEmpty(phone_num)) {
            DialogUtil.showToast(this, "手机号不能为空");
        } else if (!CheckMsgUtils.isPhone(phone_num)) {
            DialogUtil.showToast(this, "请检查手机格式");
        } else {
            changeYzmStatu();
            getYzm();
        }

        //loginSzb();
    }

    /**
     * 获取验证码方法
     */
    private void getYzm() {
        Map<String, String> map = new HashMap<String, String>();

        map.put("tel", phone_num);
        map.put("type", "2");//1代表注册验证码
        map.put("code", HttpUtil.getParam());
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, Yzm.class, URLAddress.URLBASE + URLAddress.URL_YZM, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                Yzm str = (Yzm) response;
                if (str.getResult() == 1) {
                    code_yzm = "";
                    code_yzm = str.getData().getCode() + "";
                    if (SampleApplicationLike.isDebugs)
                        DialogUtil.showToast(LoginNewActivity_two.this,""+code_yzm);
                } else {
                    //Toasts.show(LoginNewActivity_two.this, ""+str.getErr_msg(), Toast.LENGTH_SHORT);
                    DialogUtil.showToast(LoginNewActivity_two.this, "" + str.getErr_msg());
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                DialogUtil.showToast(LoginNewActivity_two.this, "获取验证码失败，再试一次吧");
            }
        });
    }

    /**
     * 验证码按钮状态改变60秒重新发送
     */
    private void changeYzmStatu() {
        loginTextYzm.setEnabled(false);

        final Handler handlerTimeTask = new Handler();
        handlerTimeTask.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (time <= 0) {
                    loginTextYzm.setEnabled(true);
                    loginTextYzm.setText("获取验证码");
                    time = 60;
                } else {
                    loginTextYzm.setText(time + "秒后重新发送");
                    handlerTimeTask.postDelayed(this, 1000);
                }
                time--;
            }
        }, 1000);

    }


    @Override
    public void onBackPressed() {
        goHome();
    }
    private void goHome(){

        if (HomeActivity.IS_LOAD){
            finish();
            return;
        }
        startActivity(new Intent(this,HomeActivity.class));
    }

    /**
     * 回车键登录
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //这里注意要作判断处理，ActionDown、ActionUp都会回调到这里，不作处理的话就会调用两次
        if (KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction()) {
            //处理事件
            loginSzb();
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}
